<template>
	<el-row :gutter="20">
		<!-- 左侧部门树 -->
		<el-col :span="4" :xs="24">
			<ContentWrap class="h-1/1">
				<el-checkbox @click="handleImprove()" style="color: red" label="待完善水表" />
				<CommunityTree @node-click="handleCommunityNodeClick" />
			</ContentWrap>
		</el-col>
		<el-col :span="20" :xs="24">
			<!-- 搜索 -->
			<ContentWrap>
				<!-- 搜索工作栏 -->
				<el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
					<el-form-item label="水表厂家" prop="factoryCode">
						<el-select v-model="queryParams.factoryCode" clearable class="!w-120px">
							<el-option v-for="dict in getStrDictOptions(DICT_TYPE.WATER_FACTORY)" :key="dict.value" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="" prop="keyWord">
						<el-input placeholder="请输入内容" v-model.trim="keyWord">
							<template #prepend>
								<el-select v-model="kType" placeholder="请选择" class="!w-120px">
									<el-option label="水表名称" value="waterName" />
									<el-option label="水表编码" value="waterNo" />
									<el-option label="水表IMEI" value="waterImei" />
									<el-option label="结算日" value="settleDay" />
								</el-select>
							</template>
						</el-input>
					</el-form-item>
					<el-form-item label="电池状态" prop="voltageStatus">
						<el-select v-model="queryParams.voltageStatus" clearable class="!w-120px">
							<el-option v-for="dict in getIntDictOptions(DICT_TYPE.VOLTAGE_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="费用状态" prop="feeStatus">
						<el-select v-model="queryParams.feeStatus" clearable class="!w-120px">
							<el-option v-for="dict in getIntDictOptions(DICT_TYPE.FEE_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="阀门状态" prop="valveStatus">
						<el-select v-model="queryParams.valveStatus" clearable class="!w-120px">
							<el-option v-for="dict in getIntDictOptions(DICT_TYPE.VALVE_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="抄收时间" prop="lastReadTime">
						<el-date-picker
							v-model="queryParams.lastReadTime"
							value-format="YYYY-MM-DD HH:mm:ss"
							type="daterange"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							class="!w-220px" />
					</el-form-item>
					<el-form-item>
						<el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
						<el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
						<el-button type="primary" plain @click="syncZhybWater()" v-if="queryParams.factoryCode == '0'" v-hasPermi="['zwsj:water:zhyb:sync']">
							<Icon icon="ep:plus" class="mr-5px" /> 抽取智慧仪表（水表）设备数据
						</el-button>
						<el-button type="primary" plain @click="openForm('create', undefined, queryParams.commId)"> <Icon icon="ep:plus" class="mr-5px" /> 新增 </el-button>
						<el-button type="success" plain @click="handleExport" :loading="exportLoading"> <Icon icon="ep:download" class="mr-5px" /> 导出 </el-button>
					</el-form-item>
				</el-form>
			</ContentWrap>

			<!-- 列表 -->
			<ContentWrap>
				<el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
					<el-table-column label="社区/水表名称/编码/安装位置" align="left" prop="meterName" min-width="330">
						<template #default="scope">
							<div v-if="scope.row.community != null">社区：{{ scope.row.community.name }}</div>
							<div v-else>社区：<span style="color: red">待分配</span></div>
							<div>
								名称：
								<el-link type="primary" @click="showWater(scope.row.id)">{{ scope.row.waterName }}</el-link>
								<dict-tag style="margin-left: 10px" :type="DICT_TYPE.WATER_FACTORY" :value="scope.row.factoryCode" />
							</div>
							<div>
								编码：
								<label>
									{{ scope.row.waterNo }}
									<span style="color: green" v-if="scope.row.onlineFlag == 1">在线</span><span style="color: red" v-if="scope.row.onlineFlag == 0">离线</span>
									<dict-tag :type="DICT_TYPE.WATER_MODE_FLAG" :value="scope.row.modeFlag" />
								</label>
							</div>
							<div v-if="scope.row.waterName != undefined && scope.row.waterName != ''">
								位置：<el-button type="primary" link :icon="Edit" @click="handleInstall(scope.row)" v-hasPermi="['zwsj:water:update']"> {{ scope.row.bindAddresses }}</el-button>
							</div>
							<div v-else>
								<span style="color: red">请先完善水表名称</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="费用状态/银联账户" align="left" width="220">
						<template #default="scope">
							<div>费用：<dict-tag :type="DICT_TYPE.FEE_STATUS" :value="scope.row.feeStatus" /></div>
							<div>余额：{{ scope.row.balance }} {{ scope.row.factoryCode == 1 ? '吨' : '元' }}</div>
							<div>
								银联：
								<el-button type="primary" link @click="showOwnMeterConfig(scope.row.ownMeterConfigRespVO.id)" v-if="scope.row.ownMeterConfigRespVO != null">
									{{ scope.row.ownMeterConfigRespVO.configRemark }}
								</el-button>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="开关/时间" align="left" width="200">
						<template #default="scope">
							<div>闸控：<dict-tag :type="DICT_TYPE.VALVE_STATUS" :value="scope.row.valveStatus" /></div>
							<div>结算日：{{ scope.row.settleDay }}</div>
							<div>时钟：{{ scope.row.waterClock }}</div>
							<div>抄收：{{ formatDate(scope.row.lastReadTime, 'YYYY-MM-DD HH:mm:ss') }}</div>
						</template>
					</el-table-column>
					<el-table-column label="流量信息" align="left" width="200">
						<template #default="scope">
							<div>累计流量：{{ formatToFraction(scope.row.totalUseData || 0) }}m³</div>
							<div>结算日流量：{{ formatToFraction(scope.row.settleDayData || 0) }}m³</div>
							<div>瞬时流量：{{ formatToFraction(scope.row.currentData || 0) }}m³</div>
							<div>上月流量：{{ formatToFraction(scope.row.lastData || 0) }}m³</div>
						</template>
					</el-table-column>
					<el-table-column label="其他信息" align="left" width="180">
						<template #default="scope">
							<div>信号强度：{{ scope.row.waterRssi }}</div>
							<div>电池电压：{{ scope.row.waterVoltage }}</div>
							<div>设备余额：{{ scope.row.balance }}</div>
							<div>电池状态：<dict-tag :type="DICT_TYPE.VOLTAGE_STATUS" :value="scope.row.voltageStatus" /></div>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" min-width="110px" fixed="right">
						<template #default="scope">
							<el-button link type="primary" @click="openForm('update', scope.row.id)" v-hasPermi="['zwsj:water:update']"> 编辑 </el-button>
							<el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['zwsj:water:delete']"> 删除 </el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
			</ContentWrap>
		</el-col>
	</el-row>

	<!-- 表单弹窗：添加/修改 -->
	<WaterView ref="showWaterRef" />
	<WaterForm ref="formRef" @success="getList" />
	<EquipBind ref="equipBindRef" @refresh-list="getList" />
	<OwnMeterConfigView ref="showOwnMeterConfigRef" />
</template>

<script setup lang="ts">
	import { Edit } from '@element-plus/icons-vue'
	import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
	import CommunityTree from '@/views/zwsj/common/CommunityTree.vue'
	import { formatDate } from '@/utils/formatTime'
	import download from '@/utils/download'
	import { WaterApi, WaterVO } from '@/api/zwsj/water'
	import WaterForm from './WaterForm.vue'
	import WaterView from './WaterView.vue'
	import EquipBind from '@/views/zwsj/equipBind/index.vue'
	import OwnMeterConfigView from '@/views/zwsj/ownMeterConfig/OwnMeterConfigView.vue'

	/** 水表信息 列表 */
	defineOptions({ name: 'Water' })

	const message = useMessage() // 消息弹窗
	const { t } = useI18n() // 国际化

	const loading = ref(true) // 列表的加载中
	const list = ref<WaterVO[]>([]) // 列表的数据
	const total = ref(0) // 列表的总页数的数

	const keyWord = ref('')
	const kType = ref('waterName')
	const queryParams = reactive({
		pageNo: 1,
		pageSize: 10,
		commId: undefined,
		factoryCode: undefined,
		modeFlag: undefined,
		waterName: undefined,
		waterNo: undefined,
		waterImei: undefined,
		lastReadTime: [],
		waterRssi: undefined,
		waterVoltage: undefined,
		settleDay: undefined,
		valveStatus: undefined,
		voltageStatus: undefined,
		feeStatus: undefined,
		useStatus: undefined,
	})
	const queryFormRef = ref() // 搜索的表单
	const exportLoading = ref(false) // 导出的加载中

	/** 查询列表 */
	const getList = async () => {
		loading.value = true
		try {
			const data = await WaterApi.getWaterPage(queryParams)
			list.value = data.list
			total.value = data.total
		} finally {
			loading.value = false
		}
	}

	const handleImprove = () => {
		queryParams.commId = undefined
		queryParams.pageNo = 1
		getList()
	}

	/** 搜索按钮操作 */
	const handleQuery = () => {
		queryParams.pageNo = 1
		getList()
	}

	/** 重置按钮操作 */
	const resetQuery = () => {
		queryFormRef.value.resetFields()
		handleQuery()
	}

	/** 添加/修改操作 */
	const formRef = ref()
	const openForm = (type: string, id?: number, commId?: number) => {
		formRef.value.open(type, id, commId)
	}

	/** 删除按钮操作 */
	const handleDelete = async (id: number) => {
		try {
			// 删除的二次确认
			await message.delConfirm()
			// 发起删除
			await WaterApi.deleteWater(id)
			message.success(t('common.delSuccess'))
			// 刷新列表
			await getList()
		} catch {}
	}

	/** 导出按钮操作 */
	const handleExport = async () => {
		try {
			// 导出的二次确认
			await message.exportConfirm()
			// 发起导出
			exportLoading.value = true
			const data = await WaterApi.exportWater(queryParams)
			download.excel(data, '水表信息.xls')
		} catch {
		} finally {
			exportLoading.value = false
		}
	}

	/** 处理区域被点击 */
	const handleCommunityNodeClick = async row => {
		queryParams.commId = row.id
		await getList()
	}

	/**
	 * 将一个整数转换为分数保留三位小数
	 * @param num
	 */
	const formatToFraction = (num: number | string | undefined): string => {
		if (typeof num === 'undefined') return '0.000'
		const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
		return (parsedNumber / 1000.0).toFixed(3)
	}

	/** 同步智慧仪表（水表）设备 */
	const syncZhybWater = async () => {
		try {
			// 同步
			await WaterApi.syncZhybWater()
			getList()
		} catch {
		} finally {
		}
	}

	/** 显示水表 */
	const showWaterRef = ref()
	const showWater = async (waterId: number) => {
		showWaterRef.value.open(waterId)
	}

	const showOwnMeterConfigRef = ref()
	const showOwnMeterConfig = async (ownMeterConfigId: number) => {
		showOwnMeterConfigRef.value.open(ownMeterConfigId)
	}

	const equipBindRef = ref()
	const handleInstall = async (row: any) => {
		let positionType = 'room'
		equipBindRef.value.open(row.id, 'water', positionType, row.commId, row.waterName)
	}

	/** 初始化 **/
	onMounted(() => {
		getList()
	})
</script>
